const router = require('koa-router')();
const moment = require('moment');

router.prefix('/message');

// 查看是否互相关注
router.get('/muattention',async(ctx,next)=>{
    let {id,receiveid} = ctx.request.query;
    console.log(id,receiveid)
    let sqlCount ='select count(unid) as count from fan where (id=? and fanId=?) || (id=? and fanId=?);';   
    let result = await ctx.db.EXCUTE(sqlCount,[id,receiveid,receiveid,id])
    let count = result[0].count;  
    console.log(count)
    if(count==2){
        ctx.body={code:200,status:'互相关注'}
    }else{
        ctx.body={code:201,status:'没有互相关注'}
    }
})

// 查看是否有陌生人消息
router.get('/getstranger',async(ctx,next)=>{
    let {id} = ctx.request.query;
    let sqlCount ='select count(id) as count from message where receiveid=? and stranger=?;';   
    let result = await ctx.db.EXCUTE(sqlCount,[id,1])
    let count = result[0].count;  
    console.log("ssssssssss",count)
    if(count==0){
        ctx.body={code:200,status:'暂无陌生人的消息'}
    }else{
        ctx.body={code:201,status:'有陌生人消息'}
    }
})

// 查看是否有陌生人消息
router.get('/getstrangermeslist',async(ctx,next)=>{
    let {id} = ctx.request.query;
    // 获取到陌生人发送的最新数据
    let sqlCount ='select * from message where receiveid=? and stranger=? and time in (select max(time) from message GROUP BY sendid) order by time desc';
    let result = await ctx.db.EXCUTE(sqlCount,[id,1])
    ctx.body={code:200,status:'success',list:result} 
})

// 删除陌生人消息
router.get('/deletestranger',async(ctx,next)=>{
    let { id,receiveid } = ctx.request.query;
    console.log(id,receiveid)
    let code;
    let status;
    let sql = 'update message set message.show = ? where (sendid=? and receiveid=?) || (sendid=? and receiveid=?)'
    try{
        let result = await ctx.db.EXCUTE(sql,[1,id,receiveid,receiveid,id])
        console.log(result.affectedRows)
        status = result.affectedRows != 0 ? 
          '删除成功':'删除失败 ';
        code = result.affectedRows != 0 ? 
          200:400;
      }catch(e){
        code = 400;
        status = '删除失败';
        console.log(e)
      } 
    ctx.body={code:code,status:status}
})

// 获取陌生人最新消息
router.get('/getlaststranger',async(ctx,next)=>{
    let {id} = ctx.request.query;
    console.log(id)
    // 获取到陌生人发送的最新数据
    let sqlCount ='select * from message where receiveid=? and stranger=? and message.show=? order by time desc';
    let result = await ctx.db.EXCUTE(sqlCount,[id,1,0])
    let newtime = moment(result[0].time).format('YYYY/MM/DD HH:mm:ss');
    let obj = result[0]
    obj.time = newtime
    ctx.body={code:200,status:'success',last:obj} 
})

module.exports = router;